import axios, { AxiosPromise, AxiosRequestConfig, AxiosResponse } from 'axios';
import { ElNotification } from 'element-plus';
import router from '@/config/routes';

import { getToken, setToken } from '@/utils/localToken';
import { useUserStore } from '@/store/user'
import refreshToken from './refresh_token'
export interface ResponseData {
	code : number;
	data ?: any;
	msg ?: string;

}


let isRefreshing = false
let subscribers = []

axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
axios.defaults.headers.get['Content-Type'] = 'application/x-www-form-urlencoded';
axios.defaults.withCredentials = true;

// create an axios instance

const service = axios.create({
	baseURL: (import.meta.env.VITE_APP_APIHOST || '') as string, // url = base url + request url
	// withCredentials: true, // send cookies when cross-domain requests
	timeout: 10000, // request timeout
})

// request interceptor
service.interceptors.request.use(
	async config => {
		// 否则，请求新的token
		config.headers['Authorization'] = await getToken()
		return config
	},
	error => {
		// do something with request error
		return Promise.reject(error)
	}
)

// 响应拦截器
service.interceptors.response.use((response) => {
	if (response.config.responseType == "arraybuffer") {
		return response.data;
	}
	// if (response.config.responseType = 'blob') {
	// 	console.log(response, 'response')
	// 	const contentDisposition = response.headers['content-disposition'];
	// 	const fileName = contentDisposition.split('filename=')[1];
	// 	const url = window.URL.createObjectURL(new Blob([response.data]));
	// 	const link = document.createElement('a');
	// 	link.href = url;
	// 	link.setAttribute('download', fileName);
	// 	document.body.appendChild(link);
	// 	link.click();
	// 	// return "下载成功"
	// }
	// console.log(response)

	const data = response.data
	const code = Number(data.code)
	// 检查错误代码并弹窗提示
	if (code == 0) {
		return response.data.result||response.data.data
	} else {
		ElNotification({
			type: 'error',
			title: `提示`,
			message: `Error: ${data.result}`,
		});

		return Promise.reject(data.result)

	}

}, async (error) => {
	// 如果返回401错误并且未刷新token，则刷新token并重新发送请求
	const originalRequest = error.config
	if (error.code == 'ECONNABORTED' && error.message.indexOf('timeout') != -1 && !originalRequest
		._retry) {
		ElNotification({
			type: 'error',
			title: `提示`,
			message: error.message,
		});
		originalRequest._retry = true
		return null;
	}
	if (error.response.status === 401 && !originalRequest._retry) {

		if (isRefreshing) {
			// 如果有其他请求正在刷新token，则等待其完成后重试
			return new Promise((resolve, reject) => {
				subscribers.push((token : string) => {
					originalRequest.headers['Authorization'] = token
					resolve(service(originalRequest))
				})
			})
		} else {
			originalRequest._retry = true
			try {
				const token = await refreshToken()
				subscribers.forEach((callback : any) =>{
					callback(token)
				} )
				originalRequest.headers['Authorization'] = token
				// 重新发送原始请求
				return service(originalRequest)
			} catch (error) {
				// 刷新token失败
				return Promise.reject(error)
			} finally {
				subscribers = []
				isRefreshing = false
				originalRequest._retry = false
			}
		}
	} else if (error.response.status == 400) {
		ElNotification({
			type: 'error',
			title: `提示`,
			message: `Error:你还没有登录，现在要登录吗`,
		});

		return Promise.reject(error.response.request.responseText)
	} else {
		ElNotification({
			type: 'error',
			title: `提示`,
			message: error.response.data,
		});

	}

	return Promise.reject(error)
})



export default service